package com.rs.controller;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.aliyuncs.exceptions.ClientException;
import com.rs.bean.PhoneCode;
import com.rs.bean.User;
import com.rs.bean.UserToken;
import com.rs.service.CodeService;
import com.rs.service.UserService;
import com.rs.service.UserTokenService;
import com.rs.util.CodeUtil;
import com.rs.util.CookieUtils;

/**
 * @ClassName: UserController
 * @Description: TODO(用户控制器)
 * @author LH
 * @date 2017年10月20日 上午9:08:40
 * 
 */
@Controller
@RequestMapping("/user")
public class UserController {

	@Autowired
	private UserService userService;

	@Autowired
	private UserTokenService userTokenService;

	@Autowired
	private CodeService codeService;

	/**
	 * @Title: login 
	 * @Description: TODO(用户登录) 
	 * @param nickname 昵称
	 * @param password 密码 
	 * @param req 请求
	 * @param resp 响应 
	 * @return void 返回类型 
	 * @throws
	 */
	@RequestMapping("/login")
	public void login(String nickname, String password, HttpServletRequest req, HttpServletResponse resp) {

		User user = userService.getUserByNickname(nickname);
		if (user == null) {
			// 用户不存在
			req.setAttribute("message", "该用户不存在，请先注册！");
			try {
				req.getRequestDispatcher("../error.jsp").forward(req, resp);
			} catch (ServletException | IOException e) {
				e.printStackTrace();
			}
		} else {
			// 用户存在
			if (!password.equals(user.getUserPwd())) {
				// 密码错误
				req.setAttribute("message", "密码错误请核对后再登录！");
				try {
					req.getRequestDispatcher("../error.jsp").forward(req, resp);
				} catch (ServletException | IOException e) {
					e.printStackTrace();
				}
			} else {
				// 登录成功
				String token = UUID.randomUUID().toString();

				// 根据昵称查询token
				UserToken result = userTokenService.getUserTokenByNickname(nickname);
				if (result == null) {
					// 把token信息添加到表里
					UserToken userToken = new UserToken();
					userToken.setNickname(nickname);
					userToken.setUserId(user.getUserId());
					userToken.setPhoto(user.getPhoto());
					userToken.setToken(token);
					userTokenService.addUserToken(userToken);
				} else {
					// 更新token值
					userTokenService.updateToken(token, nickname);
				}
				CookieUtils.setCookie(req, resp, "token", token);

				try {
					resp.sendRedirect("../userClient/html/mySpace.html");
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}

			}
		}
	}

	/**
	 * @Title: selectTokenUser 
	 * @Description: TODO(这里用一句话描述这个方法的作用) 
	 * @param request 
	 * @return EmpToken 
	 * @throws
	 */
	@RequestMapping("/selectToken")
	@ResponseBody
	public UserToken selectTokenUser(HttpServletRequest request) {
		String token = CookieUtils.getCookieValue(request, "token");
		UserToken result = userTokenService.getUserTokenByToken(token);
		return result;
	}

	
	@RequestMapping("/regist")
	public String regist(String nickname, String password, String phone,HttpServletRequest req,HttpServletResponse resp) {
		System.out.println(nickname+"nickname"+phone+"phone"+password+"passWord");
		User user = new User(nickname,phone,password);
		int result = userService.saveUser(user);
		if(result>0){
			//注册成功
			//生成token 保存token 跳转个人中心
			
			//生成token
			String token = UUID.randomUUID().toString();
			
			UserToken userToken=new UserToken();
			userToken.setNickname(nickname);
			userToken.setPhoto("default");
			userToken.setToken(token);
			userToken.setUserId(result);
			
			//保存token
			userTokenService.addUserToken(userToken);
			CookieUtils.setCookie(req, resp, "token", token);
			
			//跳转个人中心
			try {
				resp.sendRedirect("../userClient/html/mySpace.html");
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}else{
			//注册失败
			try {
				req.setAttribute("message", "服务器异常，注册失败。请稍后重试！");
				req.getRequestDispatcher("../error.jsp").forward(req, resp);
			} catch (ServletException | IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
		return null;
	}

	/**
	 * @Title: sendCode 
	 * @Description: TODO(发送验证码,添加code到数据库) 
	 * @param phone 目标手机号 
	 * @return void 返回类型 @throws
	 */
	@RequestMapping("/sendCode")
	@ResponseBody
	public void sendCode(String phone) {
		System.out.println(phone);
		// 生成六位数验证码
		int code = (int) (Math.random() * 1000000);
		String codeStr = String.valueOf(code);
		System.out.println(codeStr);
		PhoneCode phoneCode = new PhoneCode(phone, codeStr);
		
		//判断数据库是否有该手机号的记录
		String codeByPhone = codeService.getCodeByPhone(phone);
		int result;
		if(codeByPhone==null){
			//没有该手机的记录 
			// 保存验证码
			result = codeService.saveCode(phoneCode);
		}else{
			//存在该手机的记录 更新验证码
			result=codeService.updateCode(phoneCode);
		}
		//保存和更新成功 发送短信
		if (result > 0) {
			System.out.println("code" + code);
			System.out.println("phone" + phone);
			// 发送短信
			try {
				CodeUtil.send(phone, codeStr);
			} catch (ClientException e) {
				e.printStackTrace();
			}
		}
	}

	/**
	 * @Title: checkNickname 
	 * @Description: TODO(验证昵称唯一) 
	 * @param nickname 昵称 
	 * @return Map<String,Object> 返回类型 
	 * @throws
	 */

	@RequestMapping("/checkNickname")
	@ResponseBody
	public Map<String, String> checkNickname(String nickname) {
		System.out.println(nickname);
		String result = userService.checkNickname(nickname);
		if (result == null) {
			result = "0";
		}
		System.out.println(result + "jieguo");
		Map<String, String> map = new HashMap<String, String>();
		map.put("result", result);
		return map;
	}

	/**
	 * @Title: checkPhone 
	 * @Description: TODO(验证手机号唯一验证) 
	 * @param phone 手机号
	 * @return Map<String,String> 返回类型 
	 * @throws
	 */

	@RequestMapping("/checkPhone")
	@ResponseBody
	public Map<String, String> checkPhone(String phone) {
		System.out.println(phone);
		String result = userService.checkPhone(phone);
		System.out.println(result);
		Map<String, String> map = new HashMap<String, String>();
		map.put("result", result);
		return map;
	}

	/**
	 * @Title: checkCode
	 * @Description: TODO(根据手机号核对验证码) 
	 * @param phone 手机号 
	 * @param code 验证码
	 * @return Map<String,String> 返回类型 
	 * @throws
	 */
	@RequestMapping("/ckCode")
	@ResponseBody
	public Map<String, String> checkCode(String phone, String code) {
		System.out.println(phone + "phone" + code + "code");
		String result = codeService.getCodeByPhone(phone);
		Map<String, String> map = new HashMap<String, String>();
		if (code.equals(result)) {
			// 验证码正确
			map.put("result", "1");
			//删除记录
			codeService.deleteCode(phone);
		}else{
			// 验证码错误
			map.put("result", "0");
		}
		System.out.println(map.get("result") + "result");
		return map;
	}

}
